import { tool } from "@/utils/tool";
import { defineStore, createPinia } from "pinia";
import api from "@/api";
export const useAuth = defineStore("auth", {
	state: (): AuthStoreState => ({
		TOKEN: tool.get("TOKEN") || "",
		USER_INFO: tool.get("USER_INFO") || null,
		GZH_OPENID: tool.get("GZH_OPENID") || "",
		LOGIN_BACK: tool.get("LOGIN_BACK") || "",
		REDIRECT_URL: tool.get("REDIRECT_URL") || "",
	}),
	actions: {
		SET_REDIRECTURL() {
			this.REDIRECT_URL = `${window.location.origin}${window.location.pathname}`;
			tool.set(
				"REDIRECT_URL",
				`${window.location.origin}${window.location.pathname}`
			);
		},
		SET_TOKEN(token: string) {
			this.TOKEN = token;
			tool.set("TOKEN", token);
		},
		CLEAR_TOKEN() {
			this.TOKEN = "";
			tool.remove("TOKEN");
		},
		SET_USER_INFO(data: any) {
			this.USER_INFO = data;
			tool.set("USER_INFO", data);
		},
		CLEAR_USER_INFO() {
			this.USER_INFO = null;
			tool.remove("USER_INFO");
		},
		SET_LOGIN_BACK(data: string) {
			this.LOGIN_BACK = data;
			tool.set("LOGIN_BACK", data);
		},
		CLEAR_LOGIN_BACK() {
			this.LOGIN_BACK = "";
			tool.remove("LOGIN_BACK");
		},
		async GetUserInfo() {
			const res: any = await api.user.user.info.get({});
			if (res?.code === 1) {
				this.SET_USER_INFO(res.data);
			}
		},
		logout() {
			this.CLEAR_TOKEN();
			this.CLEAR_USER_INFO();
			uni.showToast({
				title: "退出登录成功",
				icon: "none",
			});
			uni.$u.sleep(1000).then(() => {
				uni.navigateBack();
			});
		},
		loginJump() {
			const History: string = this.LOGIN_BACK || "/pages/index/index";
			const switchList = [
				"/pages/index/index",
				"/pages/activity/index",
				"/pages/shop/index",
				"/pages/mine/index",
			];
			const isSwitch = switchList.findIndex(
				(item) => History.indexOf(item) !== -1
			);
			tool.remove("POPUP_FLAG");
			this.CLEAR_LOGIN_BACK();
			if (isSwitch === -1) {
				uni.redirectTo({ url: History });
			} else {
				uni.switchTab({
					url: History,
				});
			}
		},
		checkLogin() {
			if (!this.TOKEN) {
				const pages = uni.$u.pages();
				const currentPage = pages[pages.length - 1].options || {};
				const params = new URLSearchParams(currentPage).toString();
				this.SET_LOGIN_BACK(
					uni.$u.page() + (params ? `?${params}` : "")
				);
				uni.navigateTo({ url: "/pages/login/index" });
				return false;
			} else {
				return true;
			}
		},
		bindParentUser(res: any) {
			// if (!res.pid && tool.get("INVITE_USER")) {
			// 	bindParent({ pid: tool.get("INVITE_USER") });
			// }
			// if (tool.get("INVITE_DEVICE")) {
			// 	bindParent({ device_code: tool.get("INVITE_DEVICE") });
			// }
			// tool.remove("INVITE_DEVICE");
			// tool.remove("INVITE_USER");
		},
	},
	getters: {
		getToken: (state) => state.TOKEN || "",
	},
});
